package TaskModule

import (
	"time"
	"frame/logger/HLogger"
	"reflect"
	"fmt"
	"tools/IDGeneratorTools"
	"frame/utils/StringUtils"
	"strconv"
)

var logger = HLogger.GetHLogger("TaskModule")

type TaskModule struct {
	Name string
	Iterval time.Duration
	Taskfunc interface{}
}

var taskModules = make(map[string]TaskModule)


/**
注册一个task
 */
func RegisterTask(task TaskModule)(bool,error){
	taskModules[task.Name]=task
	return true,nil
}
/**
获取一个task
 */
func GetTask(name string)(TaskModule,bool){
	taskModule,found :=  taskModules[name]
	return taskModule,found
}

func GetTaskModulesCount()(int){
	return len(taskModules)
}

func ProcessTask(taskname string,context map[string]interface{}){
	var taskModule,found = GetTask(taskname)
	if(!found){
		logger.Error("执行task["+taskname+"]失败，该logic未注册")
		return
	}
	var i time.Duration = taskModule.Iterval

	t:=time.NewTimer(i)

	for{
		select {
		case <- t.C:
			//执行task
			taskfunc := reflect.ValueOf(taskModule.Taskfunc)
			if(taskfunc.Kind() != reflect.Func){
				logger.Error("执行task["+taskname+"]失败，task的Taskfunc属性并非函数")
			}

			//生成交易上下文
			var txnid,_ = IDGeneratorTools.CreateSimpleUint64()
			var txnContext = HLogger.TxnContext{Txnid:StringUtils.StrRightAlign(strconv.Itoa(int(txnid)),8)}

			var callparam = make([]reflect.Value,0,5)

			//组装callparam
			callparam = append(callparam,reflect.ValueOf(txnContext))
			callparam = append(callparam,reflect.ValueOf(&context))

			//函数调用
			var result []reflect.Value = taskfunc.Call(callparam)

			logger.InfoWithTxnContext(txnContext,"执行task["+taskname+"]完毕，执行结果为"+fmt.Sprint(result)+"")
			t.Reset(i)
		}
	}
}
